package com.itx.gatewayx.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itx.gatewayx.domain.News;
import com.itx.gatewayx.domain.NewsComment;
import com.itx.gatewayx.domain.User;
import com.itx.gatewayx.mapper.NewsCommentMapper;
import com.itx.gatewayx.mapper.NewsMapper;
import com.itx.gatewayx.service.NewsCommentService;
import com.itx.gatewayx.service.NewsService;
import com.itx.gatewayx.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 新闻评论服务实现类
 *
 * @author itx
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NewsCommentServiceImpl extends ServiceImpl<NewsCommentMapper, NewsComment> implements NewsCommentService {
    
    private final NewsCommentMapper commentMapper;
    private final NewsMapper newsMapper;
    private final UserService userService;
    private final NewsService newsService;
    
    @Override
    public IPage<NewsComment> getCommentList(Long current, Long size, String newsId) {
        Page<NewsComment> page = new Page<>(current, size);
        
        // 查询根评论
        IPage<NewsComment> commentPage = commentMapper.selectRootComments(page, newsId);
        
        // 查询每个根评论的回复
        commentPage.getRecords().forEach(this::fillReplies);
        
        return commentPage;
    }
    
    /**
     * 填充评论回复
     *
     * @param comment 评论
     */
    private void fillReplies(NewsComment comment) {
        List<NewsComment> replies = commentMapper.selectReplies(comment.getId());
        comment.setReplies(replies);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addComment(NewsComment comment) {
        // 检查新闻是否存在
        News news = newsService.getById(comment.getNewsId());
        if (news == null || news.getDelFlag() == 1) {
            return false;
        }
        
        // 设置评论属性
        comment.setParentId(0L); // 设为根评论
        comment.setReplyToUserId(0L); // 不是回复其他评论
        comment.setCreateTime(new Date());
        comment.setDelFlag(0);
        
        // 保存评论
        boolean success = this.save(comment);
        
        // 更新新闻评论数
        if (success) {
            newsMapper.updateComments(comment.getNewsId(), 1);
        }
        
        return success;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean replyComment(NewsComment comment) {
        // 检查新闻是否存在
        News news = newsService.getById(comment.getNewsId());
        if (news == null || news.getDelFlag() == 1) {
            return false;
        }
        
        // 检查父评论是否存在
        NewsComment parentComment = this.getById(comment.getParentId());
        if (parentComment == null || parentComment.getDelFlag() == 1) {
            return false;
        }
        
        // 设置评论属性
        comment.setCreateTime(new Date());
        comment.setDelFlag(0);
        
        // 保存评论
        boolean success = this.save(comment);
        
        // 更新新闻评论数
        if (success) {
            newsMapper.updateComments(comment.getNewsId(), 1);
        }
        
        return success;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteComment(Long commentId, Long userId) {
        // 检查评论是否存在
        NewsComment comment = this.getById(commentId);
        if (comment == null || comment.getDelFlag() == 1) {
            return false;
        }
        
        // 检查是否有权限删除
        if (!comment.getUserId().equals(userId)) {
            // 检查是否为管理员
            User user = userService.getById(userId);
            if (user == null || !"admin".equals(user.getRole())) {
                return false;
            }
        }
        
        // 逻辑删除
        NewsComment updateComment = new NewsComment();
        updateComment.setId(commentId);
        updateComment.setDelFlag(1);
        
        boolean success = this.updateById(updateComment);
        
        // 更新新闻评论数
        if (success) {
            newsMapper.updateComments(comment.getNewsId(), -1);
            
            // 如果是根评论，同时删除其下的回复
            if (comment.getParentId() == 0) {
                // TODO: 实现删除子评论的逻辑
            }
        }
        
        return success;
    }
    
    @Override
    public NewsComment getCommentWithReplies(Long parentId) {
        // 查询父评论
        NewsComment parentComment = this.getById(parentId);
        if (parentComment == null || parentComment.getDelFlag() == 1) {
            return null;
        }
        
        // 查询用户信息
        User user = userService.getById(parentComment.getUserId());
        if (user != null) {
            parentComment.setUsername(user.getUsername());
            parentComment.setUserAvatar(user.getAvatar());
        }
        
        // 查询回复
        List<NewsComment> replies = commentMapper.selectReplies(parentId);
        parentComment.setReplies(replies);
        
        return parentComment;
    }
} 